/*
 * @Author       : Wangjunju
 * @Date         : 2024-03-07
 * @copyleft Apache 2.0
 */
#ifndef SEMAPHORE_H
#define SEMAPHORE_H

#include <mutex>
#include <condition_variable>
#include <atomic>

class CSemaphore {
public:
    explicit CSemaphore(int count = 0) : m_count(count) {}

    void Signal() {
        std::lock_guard<std::mutex> lock(m_mtx);
        ++m_count;
        m_cv.notify_one();
    }

    void Wait() {
        std::unique_lock<std::mutex> lock(m_mtx);
        m_cv.wait(lock, [=] { return m_count > 0; });
        --m_count;
    }

private:
    std::mutex m_mtx;
    std::condition_variable m_cv;
    std::atomic<int> m_count;
};

#endif // SEMAPHORE_H